# pip3 install Kafka-python
import json
from datetime import datetime

from apscheduler.schedulers.blocking import BlockingScheduler
from kafka import KafkaProducer

from backFlush import getBackFlushData
from pumpData import getPumpModelData, getWaterModelData, getAddAlumModelData, getOzoneModelData

# 配置Kafka生产者
producer = KafkaProducer(bootstrap_servers=['10.10.102.163:9092'],
                         value_serializer=lambda m: json.dumps(m).encode('utf-8'))


def pushData():
    message = getMessage(datetime.now())
    # 发送消息到Kafka的'test'主题
    for oneIot in message:
        producer.send('SHOW_DEVICE_DATA', oneIot)
        print(oneIot)
        # 确保所有消息都被发送
        producer.flush()


def pushBackFlush():
    message = getBackFlushData(datetime.now())
    # 发送消息到Kafka的'test'主题
    for oneIot in message:
        producer.send('SHOW_DEVICE_DATA', oneIot)
        print(oneIot)
        # 确保所有消息都被发送
        producer.flush()


def getMessage(now):
    # 泵组模型数据
    pumpValues = getPumpModelData(now)
    dictMessage1 = {"deviceId": "1000001", "timestamp": now.strftime("%Y-%m-%d %H:%M:%S"), "values": pumpValues}
    dictMessage1["ratioValues"] = dictMessage1["values"]

    # 水量模型数据
    waterValues = getWaterModelData()
    dictMessage2 = {"deviceId": "1000002", "timestamp": now.strftime("%Y-%m-%d %H:%M:%S"), "values": waterValues}
    dictMessage2["ratioValues"] = dictMessage2["values"]

    # 加矾模型数据
    addAlumValues = getAddAlumModelData()
    dictMessage3 = {"deviceId": "1000003", "timestamp": now.strftime("%Y-%m-%d %H:%M:%S"), "values": addAlumValues}
    dictMessage3["ratioValues"] = dictMessage3["values"]

    # 臭氧模型数据
    ozoneValues = getOzoneModelData()
    dictMessage4 = {"deviceId": "1000004", "timestamp": now.strftime("%Y-%m-%d %H:%M:%S"), "values": ozoneValues}
    message = [dictMessage1, dictMessage2, dictMessage3, dictMessage4]
    return message


if __name__ == '__main__':
    # # 创建调度器
    # scheduler = BlockingScheduler()
    # # 添加任务，每15秒执行一次
    # scheduler.add_job(pushData, trigger='interval', seconds=15)
    # scheduler.add_job(pushBackFlush, trigger='interval', seconds=10)
    # # 启动定时任务
    # scheduler.start()
    print(getOzoneModelData())
